/**
 * 
 */
package com.geezdata.cps.base.utils;

import java.io.File;
import java.util.Random;

import org.apache.shiro.crypto.hash.Md5Hash;

/**
 * @author sszheng
 * @date 创建时间：2017年12月25日 下午2:20:13
 *
 */
public class FileUtil {
	public static String getFilename(String defaultDirectory, String fileName){
		File directory = new File(defaultDirectory);
		if(!directory.exists() || !directory.isDirectory()) {
			directory.mkdir();
		}
		
		String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
		String saveName = generateFilename(fileName);
		File file = null;
		Integer n = 10;
		while(n-- > 0){
			file = new File(defaultDirectory + "/" + saveName);
			if(file.exists() && file.isFile()){
				saveName = generateFilename(fileName);
			} else {
				break;
			}
		}
		return saveName + '.' + ext;
	}

	private static String generateFilename(String seed){
		Md5Hash hash = new Md5Hash(seed);
		String str = hash.toHex();
		String head = str.substring(9, 17);
		Random random = new Random();
		random.setSeed(System.currentTimeMillis());
		String tail = String.format("%06d", random.nextInt(1000000));
		return head + tail;
	}
}
